3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
11 * Base code for file repositories.
18 * Base class for file repositories
23 const DELETE_SOURCE
= 1;
25 const OVERWRITE_SAME
= 4;
26 const SKIP_LOCKING
= 8;
28 /** @var FileBackend */
30 /** @var Array Map of zones to config */
31 protected $zones = array();
33 var $thumbScriptUrl, $transformVia404;
34 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
35 var $fetchDescription, $initialCapital;
36 var $pathDisclosureProtection = 'simple'; // 'paranoid'
37 var $descriptionCacheExpiry, $url, $thumbUrl;
38 var $hashLevels, $deletedHashLevels;
41 * Factory functions for creating new files
42 * Override these in the base class
44 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
45 var $oldFileFactory = false;
46 var $fileFactoryKey = false, $oldFileFactoryKey = false;
48 function __construct( array $info = null ) {
49 // Verify required settings presence
52 ||
!array_key_exists( 'name', $info )
53 ||
!array_key_exists( 'backend', $info )
55 throw new MWException( __CLASS__
. " requires an array of options having both 'name' and 'backend' keys.\n" );
59 $this->name
= $info['name'];
60 if ( $info['backend'] instanceof FileBackend
) {
61 $this->backend
= $info['backend']; // useful for testing
63 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
66 // Optional settings that can have no value
67 $optionalSettings = array(
68 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
69 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
72 foreach ( $optionalSettings as $var ) {
73 if ( isset( $info[$var] ) ) {
74 $this->$var = $info[$var];
78 // Optional settings that have a default
79 $this->initialCapital
= isset( $info['initialCapital'] )
80 ?
$info['initialCapital']
81 : MWNamespace
::isCapitalized( NS_FILE
);
82 $this->url
= isset( $info['url'] )
84 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
85 if ( isset( $info['thumbUrl'] ) ) {
86 $this->thumbUrl
= $info['thumbUrl'];
88 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
90 $this->hashLevels
= isset( $info['hashLevels'] )
93 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
94 ?
$info['deletedHashLevels']
96 $this->transformVia404
= !empty( $info['transformVia404'] );
97 $this->zones
= isset( $info['zones'] )
100 // Give defaults for the basic zones...
101 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
102 if ( !isset( $this->zones
[$zone] ) ) {
103 $this->zones
[$zone] = array(
104 'container' => "{$this->name}-{$zone}",
105 'directory' => '' // container root
112 * Get the file backend instance. Use this function wisely.
114 * @return FileBackend
116 public function getBackend() {
117 return $this->backend
;
121 * Get an explanatory message if this repo is read-only.
122 * This checks if an administrator disabled writes to the backend.
124 * @return string|bool Returns false if the repo is not read-only
126 public function getReadOnlyReason() {
127 return $this->backend
->getReadOnlyReason();
131 * Check if a single zone or list of zones is defined for usage
133 * @param $doZones Array Only do a particular zones
136 protected function initZones( $doZones = array() ) {
137 $status = $this->newGood();
138 foreach ( (array)$doZones as $zone ) {
139 $root = $this->getZonePath( $zone );
140 if ( $root === null ) {
141 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
148 * Take all available measures to prevent web accessibility of new deleted
149 * directories, in case the user has not configured offline storage
154 protected function initDeletedDir( $dir ) {
155 $this->backend
->secure( // prevent web access & dir listings
156 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
160 * Determine if a string is an mwrepo:// URL
165 public static function isVirtualUrl( $url ) {
166 return substr( $url, 0, 9 ) == 'mwrepo://';
170 * Get a URL referring to this repository, with the private mwrepo protocol.
171 * The suffix, if supplied, is considered to be unencoded, and will be
172 * URL-encoded before being returned.
174 * @param $suffix string
177 public function getVirtualUrl( $suffix = false ) {
178 $path = 'mwrepo://' . $this->name
;
179 if ( $suffix !== false ) {
180 $path .= '/' . rawurlencode( $suffix );
186 * Get the URL corresponding to one of the four basic zones
188 * @param $zone String: one of: public, deleted, temp, thumb
189 * @return String or false
191 public function getZoneUrl( $zone ) {
196 return "{$this->url}/temp";
198 return false; // no public URL
200 return $this->thumbUrl
;
207 * Get the backend storage path corresponding to a virtual URL.
208 * Use this function wisely.
213 public function resolveVirtualUrl( $url ) {
214 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
215 throw new MWException( __METHOD__
.': unknown protocol' );
217 $bits = explode( '/', substr( $url, 9 ), 3 );
218 if ( count( $bits ) != 3 ) {
219 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
221 list( $repo, $zone, $rel ) = $bits;
222 if ( $repo !== $this->name
) {
223 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
225 $base = $this->getZonePath( $zone );
227 throw new MWException( __METHOD__
.": invalid zone: $zone" );
229 return $base . '/' . rawurldecode( $rel );
233 * The the storage container and base path of a zone
235 * @param $zone string
236 * @return Array (container, base path) or (null, null)
238 protected function getZoneLocation( $zone ) {
239 if ( !isset( $this->zones
[$zone] ) ) {
240 return array( null, null ); // bogus
242 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
246 * Get the storage path corresponding to one of the zones
248 * @param $zone string
249 * @return string|null Returns null if the zone is not defined
251 public function getZonePath( $zone ) {
252 list( $container, $base ) = $this->getZoneLocation( $zone );
253 if ( $container === null ||
$base === null ) {
256 $backendName = $this->backend
->getName();
257 if ( $base != '' ) { // may not be set
260 return "mwstore://$backendName/{$container}{$base}";
264 * Create a new File object from the local repository
266 * @param $title Mixed: Title object or string
267 * @param $time Mixed: Time at which the image was uploaded.
268 * If this is specified, the returned object will be an
269 * instance of the repository's old file class instead of a
270 * current file. Repositories not supporting version control
271 * should return false if this parameter is set.
272 * @return File|null A File, or null if passed an invalid Title
274 public function newFile( $title, $time = false ) {
275 $title = File
::normalizeTitle( $title );
280 if ( $this->oldFileFactory
) {
281 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
286 return call_user_func( $this->fileFactory
, $title, $this );
291 * Find an instance of the named file created at the specified time
292 * Returns false if the file does not exist. Repositories not supporting
293 * version control should return false if the time is specified.
295 * @param $title Mixed: Title object or string
296 * @param $options array Associative array of options:
297 * time: requested time for a specific file version, or false for the
298 * current version. An image object will be returned which was
299 * created at the specified time (which may be archived or current).
301 * ignoreRedirect: If true, do not follow file redirects
303 * private: If true, return restricted (deleted) files if the current
304 * user is allowed to view them. Otherwise, such files will not
306 * @return File|bool False on failure
308 public function findFile( $title, $options = array() ) {
309 $title = File
::normalizeTitle( $title );
313 $time = isset( $options['time'] ) ?
$options['time'] : false;
314 # First try the current version of the file to see if it precedes the timestamp
315 $img = $this->newFile( $title );
319 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
322 # Now try an old version of the file
323 if ( $time !== false ) {
324 $img = $this->newFile( $title, $time );
325 if ( $img && $img->exists() ) {
326 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
327 return $img; // always OK
328 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
335 if ( !empty( $options['ignoreRedirect'] ) ) {
338 $redir = $this->checkRedirect( $title );
339 if ( $redir && $title->getNamespace() == NS_FILE
) {
340 $img = $this->newFile( $redir );
344 if ( $img->exists() ) {
345 $img->redirectedFrom( $title->getDBkey() );
353 * Find many files at once.
355 * @param $items array An array of titles, or an array of findFile() options with
356 * the "title" option giving the title. Example:
358 * $findItem = array( 'title' => $title, 'private' => true );
359 * $findBatch = array( $findItem );
360 * $repo->findFiles( $findBatch );
363 public function findFiles( array $items ) {
365 foreach ( $items as $item ) {
366 if ( is_array( $item ) ) {
367 $title = $item['title'];
369 unset( $options['title'] );
374 $file = $this->findFile( $title, $options );
376 $result[$file->getTitle()->getDBkey()] = $file;
383 * Find an instance of the file with this key, created at the specified time
384 * Returns false if the file does not exist. Repositories not supporting
385 * version control should return false if the time is specified.
387 * @param $sha1 String base 36 SHA-1 hash
388 * @param $options array Option array, same as findFile().
389 * @return File|bool False on failure
391 public function findFileFromKey( $sha1, $options = array() ) {
392 $time = isset( $options['time'] ) ?
$options['time'] : false;
393 # First try to find a matching current version of a file...
394 if ( $this->fileFactoryKey
) {
395 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
397 return false; // find-by-sha1 not supported
399 if ( $img && $img->exists() ) {
402 # Now try to find a matching old version of a file...
403 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
404 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
405 if ( $img && $img->exists() ) {
406 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
407 return $img; // always OK
408 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
417 * Get an array or iterator of file objects for files that have a given
418 * SHA-1 content hash.
423 public function findBySha1( $hash ) {
428 * Get the public root URL of the repository
432 public function getRootUrl() {
437 * Get the URL of thumb.php
441 public function getThumbScriptUrl() {
442 return $this->thumbScriptUrl
;
446 * Returns true if the repository can transform files via a 404 handler
450 public function canTransformVia404() {
451 return $this->transformVia404
;
455 * Get the name of an image from its title object
457 * @param $title Title
460 public function getNameFromTitle( Title
$title ) {
462 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
463 $name = $title->getUserCaseDBKey();
464 if ( $this->initialCapital
) {
465 $name = $wgContLang->ucfirst( $name );
468 $name = $title->getDBkey();
474 * Get the public zone root storage directory of the repository
478 public function getRootDirectory() {
479 return $this->getZonePath( 'public' );
483 * Get a relative path including trailing slash, e.g. f/fa/
484 * If the repo is not hashed, returns an empty string
486 * @param $name string
489 public function getHashPath( $name ) {
490 return self
::getHashPathForLevel( $name, $this->hashLevels
);
498 protected static function getHashPathForLevel( $name, $levels ) {
499 if ( $levels == 0 ) {
502 $hash = md5( $name );
504 for ( $i = 1; $i <= $levels; $i++
) {
505 $path .= substr( $hash, 0, $i ) . '/';
512 * Get the number of hash directory levels
516 public function getHashLevels() {
517 return $this->hashLevels
;
521 * Get the name of this repository, as specified by $info['name]' to the constructor
525 public function getName() {
530 * Make an url to this repo
532 * @param $query mixed Query string to append
533 * @param $entry string Entry point; defaults to index
534 * @return string|bool False on failure
536 public function makeUrl( $query = '', $entry = 'index' ) {
537 if ( isset( $this->scriptDirUrl
) ) {
538 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
539 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
545 * Get the URL of an image description page. May return false if it is
546 * unknown or not applicable. In general this should only be called by the
547 * File class, since it may return invalid results for certain kinds of
548 * repositories. Use File::getDescriptionUrl() in user code.
550 * In particular, it uses the article paths as specified to the repository
551 * constructor, whereas local repositories use the local Title functions.
553 * @param $name string
556 public function getDescriptionUrl( $name ) {
557 $encName = wfUrlencode( $name );
558 if ( !is_null( $this->descBaseUrl
) ) {
559 # "http://example.com/wiki/Image:"
560 return $this->descBaseUrl
. $encName;
562 if ( !is_null( $this->articleUrl
) ) {
563 # "http://example.com/wiki/$1"
565 # We use "Image:" as the canonical namespace for
566 # compatibility across all MediaWiki versions.
567 return str_replace( '$1',
568 "Image:$encName", $this->articleUrl
);
570 if ( !is_null( $this->scriptDirUrl
) ) {
571 # "http://example.com/w"
573 # We use "Image:" as the canonical namespace for
574 # compatibility across all MediaWiki versions,
575 # and just sort of hope index.php is right. ;)
576 return $this->makeUrl( "title=Image:$encName" );
582 * Get the URL of the content-only fragment of the description page. For
583 * MediaWiki this means action=render. This should only be called by the
584 * repository's file class, since it may return invalid results. User code
585 * should use File::getDescriptionText().
587 * @param $name String: name of image to fetch
588 * @param $lang String: language to fetch it in, if any.
591 public function getDescriptionRenderUrl( $name, $lang = null ) {
592 $query = 'action=render';
593 if ( !is_null( $lang ) ) {
594 $query .= '&uselang=' . $lang;
596 if ( isset( $this->scriptDirUrl
) ) {
597 return $this->makeUrl(
599 wfUrlencode( 'Image:' . $name ) .
602 $descUrl = $this->getDescriptionUrl( $name );
604 return wfAppendQuery( $descUrl, $query );
612 * Get the URL of the stylesheet to apply to description pages
614 * @return string|bool False on failure
616 public function getDescriptionStylesheetUrl() {
617 if ( isset( $this->scriptDirUrl
) ) {
618 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
619 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
625 * Store a file to a given destination.
627 * @param $srcPath String: source FS path, storage path, or virtual URL
628 * @param $dstZone String: destination zone
629 * @param $dstRel String: destination relative path
630 * @param $flags Integer: bitwise combination of the following flags:
631 * self::DELETE_SOURCE Delete the source file after upload
632 * self::OVERWRITE Overwrite an existing destination file instead of failing
633 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
634 * same contents as the source
635 * self::SKIP_LOCKING Skip any file locking when doing the store
636 * @return FileRepoStatus
638 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
639 $this->assertWritableRepo(); // fail out if read-only
641 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
642 if ( $status->successCount
== 0 ) {
650 * Store a batch of files
652 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
653 * @param $flags Integer: bitwise combination of the following flags:
654 * self::DELETE_SOURCE Delete the source file after upload
655 * self::OVERWRITE Overwrite an existing destination file instead of failing
656 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
657 * same contents as the source
658 * self::SKIP_LOCKING Skip any file locking when doing the store
659 * @return FileRepoStatus
661 public function storeBatch( array $triplets, $flags = 0 ) {
662 $this->assertWritableRepo(); // fail out if read-only
664 $status = $this->newGood();
665 $backend = $this->backend
; // convenience
667 $operations = array();
668 $sourceFSFilesToDelete = array(); // cleanup for disk source files
669 // Validate each triplet and get the store operation...
670 foreach ( $triplets as $triplet ) {
671 list( $srcPath, $dstZone, $dstRel ) = $triplet;
673 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
676 // Resolve destination path
677 $root = $this->getZonePath( $dstZone );
679 throw new MWException( "Invalid zone: $dstZone" );
681 if ( !$this->validateFilename( $dstRel ) ) {
682 throw new MWException( 'Validation error in $dstRel' );
684 $dstPath = "$root/$dstRel";
685 $dstDir = dirname( $dstPath );
686 // Create destination directories for this triplet
687 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
688 return $this->newFatal( 'directorycreateerror', $dstDir );
691 if ( $dstZone == 'deleted' ) {
692 $this->initDeletedDir( $dstDir );
695 // Resolve source to a storage path if virtual
696 if ( self
::isVirtualUrl( $srcPath ) ) {
697 $srcPath = $this->resolveVirtualUrl( $srcPath );
700 // Get the appropriate file operation
701 if ( FileBackend
::isStoragePath( $srcPath ) ) {
702 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
705 if ( $flags & self
::DELETE_SOURCE
) {
706 $sourceFSFilesToDelete[] = $srcPath;
709 $operations[] = array(
713 'overwrite' => $flags & self
::OVERWRITE
,
714 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
718 // Execute the store operation for each triplet
719 $opts = array( 'force' => true );
720 if ( $flags & self
::SKIP_LOCKING
) {
721 $opts['nonLocking'] = true;
723 $status->merge( $backend->doOperations( $operations, $opts ) );
724 // Cleanup for disk source files...
725 foreach ( $sourceFSFilesToDelete as $file ) {
726 wfSuppressWarnings();
727 unlink( $file ); // FS cleanup
735 * Deletes a batch of files.
736 * Each file can be a (zone, rel) pair, virtual url, storage path.
737 * It will try to delete each file, but ignores any errors that may occur.
739 * @param $pairs array List of files to delete
740 * @param $flags Integer: bitwise combination of the following flags:
741 * self::SKIP_LOCKING Skip any file locking when doing the deletions
742 * @return FileRepoStatus
744 public function cleanupBatch( array $files, $flags = 0 ) {
745 $this->assertWritableRepo(); // fail out if read-only
747 $status = $this->newGood();
749 $operations = array();
750 foreach ( $files as $path ) {
751 if ( is_array( $path ) ) {
752 // This is a pair, extract it
753 list( $zone, $rel ) = $path;
754 $path = $this->getZonePath( $zone ) . "/$rel";
756 // Resolve source to a storage path if virtual
757 if ( self
::isVirtualUrl( $path ) ) {
758 $path = $this->resolveVirtualUrl( $path );
761 $operations[] = array( 'op' => 'delete', 'src' => $path );
763 // Actually delete files from storage...
764 $opts = array( 'force' => true );
765 if ( $flags & self
::SKIP_LOCKING
) {
766 $opts['nonLocking'] = true;
768 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
774 * Pick a random name in the temp zone and store a file to it.
775 * Returns a FileRepoStatus object with the file Virtual URL in the value,
776 * file can later be disposed using FileRepo::freeTemp().
778 * @param $originalName String: the base name of the file as specified
779 * by the user. The file extension will be maintained.
780 * @param $srcPath String: the current location of the file.
781 * @return FileRepoStatus object with the URL in the value.
783 public function storeTemp( $originalName, $srcPath ) {
784 $this->assertWritableRepo(); // fail out if read-only
786 $date = gmdate( "YmdHis" );
787 $hashPath = $this->getHashPath( $originalName );
788 $dstRel = "{$hashPath}{$date}!{$originalName}";
789 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
791 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
792 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
798 * Concatenate a list of files into a target file location.
800 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
801 * @param $dstPath String Target file system path
802 * @param $flags Integer: bitwise combination of the following flags:
803 * self::DELETE_SOURCE Delete the source files
804 * @return FileRepoStatus
806 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
807 $this->assertWritableRepo(); // fail out if read-only
809 $status = $this->newGood();
812 $deleteOperations = array(); // post-concatenate ops
813 foreach ( $srcPaths as $srcPath ) {
814 // Resolve source to a storage path if virtual
815 $source = $this->resolveToStoragePath( $srcPath );
816 $sources[] = $source; // chunk to merge
817 if ( $flags & self
::DELETE_SOURCE
) {
818 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
822 // Concatenate the chunks into one FS file
823 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
824 $status->merge( $this->backend
->concatenate( $params ) );
825 if ( !$status->isOK() ) {
829 // Delete the sources if required
830 if ( $deleteOperations ) {
831 $opts = array( 'force' => true );
832 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
835 // Make sure status is OK, despite any $deleteOperations fatals
836 $status->setResult( true );
842 * Remove a temporary file or mark it for garbage collection
844 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
845 * @return Boolean: true on success, false on failure
847 public function freeTemp( $virtualUrl ) {
848 $this->assertWritableRepo(); // fail out if read-only
850 $temp = "mwrepo://{$this->name}/temp";
851 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
852 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
855 $path = $this->resolveVirtualUrl( $virtualUrl );
857 return $this->cleanupBatch( array( $path ), self
::SKIP_LOCKING
)->isOK();
861 * Copy or move a file either from a storage path, virtual URL,
862 * or FS path, into this repository at the specified destination location.
864 * Returns a FileRepoStatus object. On success, the value contains "new" or
865 * "archived", to indicate whether the file was new with that name.
867 * @param $srcPath String: the source FS path, storage path, or URL
868 * @param $dstRel String: the destination relative path
869 * @param $archiveRel String: the relative path where the existing file is to
870 * be archived, if there is one. Relative to the public zone root.
871 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
872 * that the source file should be deleted if possible
873 * @return FileRepoStatus
875 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
876 $this->assertWritableRepo(); // fail out if read-only
878 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
879 if ( $status->successCount
== 0 ) {
882 if ( isset( $status->value
[0] ) ) {
883 $status->value
= $status->value
[0];
885 $status->value
= false;
892 * Publish a batch of files
894 * @param $triplets Array: (source, dest, archive) triplets as per publish()
895 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
896 * that the source files should be deleted if possible
897 * @return FileRepoStatus
899 public function publishBatch( array $triplets, $flags = 0 ) {
900 $this->assertWritableRepo(); // fail out if read-only
902 $backend = $this->backend
; // convenience
903 // Try creating directories
904 $status = $this->initZones( 'public' );
905 if ( !$status->isOK() ) {
909 $status = $this->newGood( array() );
911 $operations = array();
912 $sourceFSFilesToDelete = array(); // cleanup for disk source files
913 // Validate each triplet and get the store operation...
914 foreach ( $triplets as $i => $triplet ) {
915 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
916 // Resolve source to a storage path if virtual
917 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
918 $srcPath = $this->resolveVirtualUrl( $srcPath );
920 if ( !$this->validateFilename( $dstRel ) ) {
921 throw new MWException( 'Validation error in $dstRel' );
923 if ( !$this->validateFilename( $archiveRel ) ) {
924 throw new MWException( 'Validation error in $archiveRel' );
927 $publicRoot = $this->getZonePath( 'public' );
928 $dstPath = "$publicRoot/$dstRel";
929 $archivePath = "$publicRoot/$archiveRel";
931 $dstDir = dirname( $dstPath );
932 $archiveDir = dirname( $archivePath );
933 // Abort immediately on directory creation errors since they're likely to be repetitive
934 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
935 return $this->newFatal( 'directorycreateerror', $dstDir );
937 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
938 return $this->newFatal( 'directorycreateerror', $archiveDir );
941 // Archive destination file if it exists
942 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
943 // Check if the archive file exists
944 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
945 // unlinks the destination file if it exists. DB-based synchronisation in
946 // publishBatch's caller should prevent races. In Windows there's no
947 // problem because the rename primitive fails if the destination exists.
948 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
949 $operations[] = array( 'op' => 'null' );
952 $operations[] = array(
955 'dst' => $archivePath
958 $status->value
[$i] = 'archived';
960 $status->value
[$i] = 'new';
962 // Copy (or move) the source file to the destination
963 if ( FileBackend
::isStoragePath( $srcPath ) ) {
964 if ( $flags & self
::DELETE_SOURCE
) {
965 $operations[] = array(
971 $operations[] = array(
977 } else { // FS source path
978 $operations[] = array(
983 if ( $flags & self
::DELETE_SOURCE
) {
984 $sourceFSFilesToDelete[] = $srcPath;
989 // Execute the operations for each triplet
990 $opts = array( 'force' => true );
991 $status->merge( $backend->doOperations( $operations, $opts ) );
992 // Cleanup for disk source files...
993 foreach ( $sourceFSFilesToDelete as $file ) {
994 wfSuppressWarnings();
995 unlink( $file ); // FS cleanup
1003 * Checks existence of a a file
1005 * @param $file string Virtual URL (or storage path) of file to check
1008 public function fileExists( $file ) {
1009 $result = $this->fileExistsBatch( array( $file ) );
1014 * Checks existence of an array of files.
1016 * @param $files Array: Virtual URLs (or storage paths) of files to check
1017 * @return array|bool Either array of files and existence flags, or false
1019 public function fileExistsBatch( array $files ) {
1021 foreach ( $files as $key => $file ) {
1022 if ( self
::isVirtualUrl( $file ) ) {
1023 $file = $this->resolveVirtualUrl( $file );
1025 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1031 * Move a file to the deletion archive.
1032 * If no valid deletion archive exists, this may either delete the file
1033 * or throw an exception, depending on the preference of the repository
1035 * @param $srcRel Mixed: relative path for the file to be deleted
1036 * @param $archiveRel Mixed: relative path for the archive location.
1037 * Relative to a private archive directory.
1038 * @return FileRepoStatus object
1040 public function delete( $srcRel, $archiveRel ) {
1041 $this->assertWritableRepo(); // fail out if read-only
1043 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1047 * Move a group of files to the deletion archive.
1049 * If no valid deletion archive is configured, this may either delete the
1050 * file or throw an exception, depending on the preference of the repository.
1052 * The overwrite policy is determined by the repository -- currently LocalRepo
1053 * assumes a naming scheme in the deleted zone based on content hash, as
1054 * opposed to the public zone which is assumed to be unique.
1056 * @param $sourceDestPairs Array of source/destination pairs. Each element
1057 * is a two-element array containing the source file path relative to the
1058 * public root in the first element, and the archive file path relative
1059 * to the deleted zone root in the second element.
1060 * @return FileRepoStatus
1062 public function deleteBatch( array $sourceDestPairs ) {
1063 $this->assertWritableRepo(); // fail out if read-only
1065 // Try creating directories
1066 $status = $this->initZones( array( 'public', 'deleted' ) );
1067 if ( !$status->isOK() ) {
1071 $status = $this->newGood();
1073 $backend = $this->backend
; // convenience
1074 $operations = array();
1075 // Validate filenames and create archive directories
1076 foreach ( $sourceDestPairs as $pair ) {
1077 list( $srcRel, $archiveRel ) = $pair;
1078 if ( !$this->validateFilename( $srcRel ) ) {
1079 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1080 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1081 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1084 $publicRoot = $this->getZonePath( 'public' );
1085 $srcPath = "{$publicRoot}/$srcRel";
1087 $deletedRoot = $this->getZonePath( 'deleted' );
1088 $archivePath = "{$deletedRoot}/{$archiveRel}";
1089 $archiveDir = dirname( $archivePath ); // does not touch FS
1091 // Create destination directories
1092 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1093 return $this->newFatal( 'directorycreateerror', $archiveDir );
1095 $this->initDeletedDir( $archiveDir );
1097 $operations[] = array(
1100 'dst' => $archivePath,
1101 // We may have 2+ identical files being deleted,
1102 // all of which will map to the same destination file
1103 'overwriteSame' => true // also see bug 31792
1107 // Move the files by execute the operations for each pair.
1108 // We're now committed to returning an OK result, which will
1109 // lead to the files being moved in the DB also.
1110 $opts = array( 'force' => true );
1111 $status->merge( $backend->doOperations( $operations, $opts ) );
1117 * Delete files in the deleted directory if they are not referenced in the filearchive table
1121 public function cleanupDeletedBatch( array $storageKeys ) {
1122 $this->assertWritableRepo();
1126 * Get a relative path for a deletion archive key,
1127 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1131 public function getDeletedHashPath( $key ) {
1133 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1134 $path .= $key[$i] . '/';
1140 * If a path is a virtual URL, resolve it to a storage path.
1141 * Otherwise, just return the path as it is.
1143 * @param $path string
1145 * @throws MWException
1147 protected function resolveToStoragePath( $path ) {
1148 if ( $this->isVirtualUrl( $path ) ) {
1149 return $this->resolveVirtualUrl( $path );
1155 * Get a local FS copy of a file with a given virtual URL/storage path.
1156 * Temporary files may be purged when the file object falls out of scope.
1158 * @param $virtualUrl string
1159 * @return TempFSFile|null Returns null on failure
1161 public function getLocalCopy( $virtualUrl ) {
1162 $path = $this->resolveToStoragePath( $virtualUrl );
1163 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1167 * Get a local FS file with a given virtual URL/storage path.
1168 * The file is either an original or a copy. It should not be changed.
1169 * Temporary files may be purged when the file object falls out of scope.
1171 * @param $virtualUrl string
1172 * @return FSFile|null Returns null on failure.
1174 public function getLocalReference( $virtualUrl ) {
1175 $path = $this->resolveToStoragePath( $virtualUrl );
1176 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1180 * Get properties of a file with a given virtual URL/storage path.
1181 * Properties should ultimately be obtained via FSFile::getProps().
1183 * @param $virtualUrl string
1186 public function getFileProps( $virtualUrl ) {
1187 $path = $this->resolveToStoragePath( $virtualUrl );
1188 return $this->backend
->getFileProps( array( 'src' => $path ) );
1192 * Get the timestamp of a file with a given virtual URL/storage path
1194 * @param $virtualUrl string
1195 * @return string|bool False on failure
1197 public function getFileTimestamp( $virtualUrl ) {
1198 $path = $this->resolveToStoragePath( $virtualUrl );
1199 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1203 * Get the sha1 of a file with a given virtual URL/storage path
1205 * @param $virtualUrl string
1206 * @return string|bool
1208 public function getFileSha1( $virtualUrl ) {
1209 $path = $this->resolveToStoragePath( $virtualUrl );
1210 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1214 return $tmpFile->getSha1Base36();
1218 * Attempt to stream a file with the given virtual URL/storage path
1220 * @param $virtualUrl string
1221 * @param $headers Array Additional HTTP headers to send on success
1222 * @return bool Success
1224 public function streamFile( $virtualUrl, $headers = array() ) {
1225 $path = $this->resolveToStoragePath( $virtualUrl );
1226 $params = array( 'src' => $path, 'headers' => $headers );
1227 return $this->backend
->streamFile( $params )->isOK();
1231 * Call a callback function for every public regular file in the repository.
1232 * This only acts on the current version of files, not any old versions.
1233 * May use either the database or the filesystem.
1235 * @param $callback Array|string
1238 public function enumFiles( $callback ) {
1239 $this->enumFilesInStorage( $callback );
1243 * Call a callback function for every public file in the repository.
1244 * May use either the database or the filesystem.
1246 * @param $callback Array|string
1249 protected function enumFilesInStorage( $callback ) {
1250 $publicRoot = $this->getZonePath( 'public' );
1251 $numDirs = 1 << ( $this->hashLevels
* 4 );
1252 // Use a priori assumptions about directory structure
1253 // to reduce the tree height of the scanning process.
1254 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1255 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1256 $path = $publicRoot;
1257 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1258 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1260 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1261 foreach ( $iterator as $name ) {
1262 // Each item returned is a public file
1263 call_user_func( $callback, "{$path}/{$name}" );
1269 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1271 * @param $filename string
1274 public function validateFilename( $filename ) {
1275 if ( strval( $filename ) == '' ) {
1278 return FileBackend
::isPathTraversalFree( $filename );
1282 * Get a callback function to use for cleaning error message parameters
1286 function getErrorCleanupFunction() {
1287 switch ( $this->pathDisclosureProtection
) {
1289 case 'simple': // b/c
1290 $callback = array( $this, 'passThrough' );
1292 default: // 'paranoid'
1293 $callback = array( $this, 'paranoidClean' );
1299 * Path disclosure protection function
1301 * @param $param string
1304 function paranoidClean( $param ) {
1309 * Path disclosure protection function
1311 * @param $param string
1314 function passThrough( $param ) {
1319 * Create a new fatal error
1321 * @return FileRepoStatus
1323 public function newFatal( $message /*, parameters...*/ ) {
1324 $params = func_get_args();
1325 array_unshift( $params, $this );
1326 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1330 * Create a new good result
1332 * @return FileRepoStatus
1334 public function newGood( $value = null ) {
1335 return FileRepoStatus
::newGood( $this, $value );
1339 * Checks if there is a redirect named as $title. If there is, return the
1340 * title object. If not, return false.
1343 * @param $title Title of image
1346 public function checkRedirect( Title
$title ) {
1351 * Invalidates image redirect cache related to that image
1352 * Doesn't do anything for repositories that don't support image redirects.
1355 * @param $title Title of image
1357 public function invalidateImageRedirect( Title
$title ) {}
1360 * Get the human-readable name of the repo
1364 public function getDisplayName() {
1365 // We don't name our own repo, return nothing
1366 if ( $this->isLocal() ) {
1369 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1370 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1374 * Returns true if this the local file repository.
1378 public function isLocal() {
1379 return $this->getName() == 'local';
1383 * Get a key on the primary cache for this repository.
1384 * Returns false if the repository's cache is not accessible at this site.
1385 * The parameters are the parts of the key, as for wfMemcKey().
1390 public function getSharedCacheKey( /*...*/ ) {
1395 * Get a key for this repo in the local cache domain. These cache keys are
1396 * not shared with remote instances of the repo.
1397 * The parameters are the parts of the key, as for wfMemcKey().
1401 public function getLocalCacheKey( /*...*/ ) {
1402 $args = func_get_args();
1403 array_unshift( $args, 'filerepo', $this->getName() );
1404 return call_user_func_array( 'wfMemcKey', $args );
1408 * Get an UploadStash associated with this repo.
1410 * @return UploadStash
1412 public function getUploadStash() {
1413 return new UploadStash( $this );
1417 * Throw an exception if this repo is read-only by design.
1418 * This does not and should not check getReadOnlyReason().
1421 * @throws MWException
1423 protected function assertWritableRepo() {}